package com.ys.malini.util;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;

public class PictureUpLoad{
	private PictureUpLoad() {
	}

	public static boolean isValidFile(String fileName) {
		String[] validFiles = { "gif", "jpg", "jpeg", "jpe", "bmp", "png",
				"txt/plain", "text", "doc", "rar" };
		boolean ret = false;
		for (int i = 0; i < validFiles.length; i++) {
			if (fileName.toLowerCase().endsWith(validFiles[i])) {
				ret = true;
				break;
			}
		}
		return ret;
	}

	public static String rebuildFileName(String fileName) {
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
				"yyyyMMddHHmmss");
		java.util.Date date = new java.util.Date();
		return sdf.format(date) + "_" + fileName;
	}
	
	/*生成缩略图文件名*/
	public static String generateSmallPic(String fileName) {
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
				"yyyyMMddHHmmss");
		java.util.Date date = new java.util.Date();
		return sdf.format(date) + "-" + fileName;
	}
	
	private static String lianjieFileName(String fileName) {
		return " " + fileName;
	}

	public static boolean isDirectoryExists(String path) {
		java.io.File file = new File(path);
		if (!file.exists()) {
			return file.mkdir();
		} else
			return true;
	}

	private static String[] getFileName(String filesName) {
		Pattern x = Pattern.compile("\\w*\\s+\\w*");
		String[] fileName = filesName.split("\\s+");
		Matcher t = x.matcher(filesName);
		System.out.println(t.matches());
		return fileName;
	}

	public static String fileUpLoad(ActionForm form,HttpServletRequest request, 
			HttpServletResponse response,String bigClassType,String midClassType,String smaClassType)
			throws Exception {
		String path = "";
		String savepath="";
		String fileName = "";
		MultipartRequestHandler handle = form.getMultipartRequestHandler();
		Hashtable hashTable = handle.getFileElements();
		Collection cln = hashTable.values();
		Iterator iterator = cln.iterator();
		
		while (iterator.hasNext()) {
			FormFile file = (FormFile) iterator.next();
			/* 设置保存路径和文件夹绝对路径 */
			path = request.getRealPath("/") + Constant.pictureDirectory + File.separator; 
			savepath=Constant.pictureDirectory + File.separator;
			if(bigClassType!=null&&!"".equals(bigClassType)){
				savepath += bigClassType + File.separator;
				path += bigClassType + File.separator;
			}
			if(midClassType!=null&&!"".equals(midClassType)){
				savepath += midClassType + File.separator;
				path += midClassType + File.separator;
			}
			if(smaClassType!=null&&!"".equals(smaClassType)){
				savepath += smaClassType + File.separator;
				path += smaClassType + File.separator;
			}
			
			/* 路径不存在，创建文件夹 */
			if (isDirectoryExists(path) == false){
				File fileDis = new File(path);
				fileDis.mkdirs();
			}
			if (file.getFileName() == null)
				return null;
			if (file.getFileName().equals("")){
				continue;
			}
			if (file.getFileSize() > Constant.pictureSize)
				return null;
			if (!isValidFile(file.getFileName()))
				return null;
			try {
				String pathSrc = path + rebuildFileName(file.getFileName());
				String savepathsrc = savepath+rebuildFileName(file.getFileName());
				
				InputStream in = file.getInputStream();
				OutputStream out = new FileOutputStream(pathSrc);// "/"表示保存的路径可以修改为"load/"
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
					out.write(buffer, 0, bytesRead);
				}
				String pathDest = path + generateSmallPic(file.getFileName());
				String savepathDest = savepath+ generateSmallPic(file.getFileName());
					
				copyfile(pathSrc, pathDest);
				/*生成缩略图*/
				File stadimgfile2 = new File(pathSrc);
				/*图片缓存*/
				BufferedImage img2 = ImageIO.read(stadimgfile2);
				/*得到图片的宽和高*/
				double width = img2.getWidth();
				double height = img2.getHeight();
				double rateh = Constant.miniheight / height;
				double ratew = Constant.miniwidth / width;
				/*获得适合的缩放比率，即以在规定缩略尺寸中完整显示图片内容的同时又保证最大的缩放比率*/
				double rate = Math.min(ratew, rateh);
				rate = (Math.rint((rate * 100) + 0.5)) / 100;
				BufferedImage imgmini = new BufferedImage(Constant.miniwidth,
						Constant.miniheight, BufferedImage.TYPE_USHORT_565_RGB);

				Graphics2D gmini = imgmini.createGraphics();
				gmini.setBackground(Color.darkGray);
				gmini.clearRect(0, 0, Constant.miniwidth, Constant.miniheight);
				AffineTransform trans = new AffineTransform();
				trans.scale(rate, rate);
				AffineTransformOp op = new AffineTransformOp(trans,
						AffineTransformOp.TYPE_BILINEAR);
				gmini.drawImage(img2, op, (int) (Constant.miniwidth - (width * rate)) / 2,
						(int) (Constant.miniheight - (height * rate)) / 2);
				ImageIO.write(imgmini, "jpg", stadimgfile2);
				
				if(fileName==""){
					fileName = savepathsrc+"@"+savepathDest;
				}else{
					fileName = fileName + "#" +savepathsrc+"@"+savepathDest;
				}
				out.close();
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		System.out.println("fileName===="+fileName);
		return fileName;
	}
	public static void copyfile(String pathSrc, String pathDest)
			throws IOException {
		FileInputStream fi = new FileInputStream(pathSrc);
		FileOutputStream fo = new FileOutputStream(pathDest);
		byte data[] = new byte[fi.available()];
		fi.read(data);
		fo.write(data);
		fi.close();
		fo.close();
	} 
} 
	

